<template>
  <view class="todo-detail">
    <view class="header">
      <text class="title">{{ form.title }}</text>
    </view>
    <view class="content" v-html="form.content"></view>
    <view class="tagArea">
      <u-tag
        v-if="form.classification"
        :text="form.classification.name"
        shape="square"
        size="mini"
      />
      <u-tag
        type="warning"
        text="进行中"
        size="mini"
        v-if="form.status === 0"
      />
      <u-tag type="success" text="已完成" size="mini" v-if="form.status == 1" />
    </view>
    <view class="answerInputArea">
      <view class="answerInputAreaTitle">
        <text>
          <u-icon name="edit-pen" color="#2979ff" size="28"></u-icon>
          操作
        </text>
        <view class="ndt-right" @click="show = true">
          <u-icon name="more-dot-fill" size="28"></u-icon>
        </view>
      </view>
      <view class="answerInputerAreaContent">
        <view
          v-if="form.status === 0"
          class="customButton styleButton1"
          @tap="toAddProcess('')"
          >填写进展</view
        >
        <view
          class="customButton styleButton2"
          v-if="!form.status"
          @tap="toCompleteTodo(1)"
          >完成待办</view
        >
        <view v-else class="customButton styleButton2" @tap="toCompleteTodo(0)"
          >取消完成</view
        >
      </view>
    </view>

    <template v-if="data.list.length > 0">
      <view class="processListArea">
        <view class="processListAreaTitle">
          <u-icon name="order" color="#2979ff" size="28"></u-icon>
          历史进展
        </view>
        <view class="alaItem" v-for="item in data.list" :key="item._id">
          <!-- <view class="alaItemTitle">123</view> -->
          <view class="answerItemContent">{{ item.content }}</view>
          <view class="answerItemTime">
            <text>{{ item.dateTime }}</text>
            <view class="rightIcon" @tap="toShowProcess(item)">
              <u-icon name="more-dot-fill" size="28"></u-icon>
            </view>
          </view>
        </view>
      </view>
      <u-loadmore
        :status="data.loadmore"
        :loadText="{
          loadmore: '点击加载更多',
          loading: '正在加载',
          nomore: '没有更多了',
        }"
        @loadmore="nextPage"
      />
    </template>
    <!-- 操作弹窗 -->
    <u-action-sheet
      :list="[{ text: '编辑待办' }, { text: '删除待办' }]"
      v-model="show"
      @click="clickAction"
    ></u-action-sheet>
    <!-- 操作弹窗 -->
    <u-action-sheet
      :list="[{ text: '编辑待办进展' }, { text: '删除待办进展' }]"
      v-model="showProcess"
      @click="clickActionProcess"
    ></u-action-sheet>

    <!-- 填写进展弹窗 -->
    <dfb-pop-input
      :title="popInputTitle"
      :content="popInputContent"
      placeholder="请填写进展"
      :rules="rules"
      :default-value="popInputDefaultValue"
      v-model:show="showPopInput"
      @confirm="submitTodoProcess"
    />
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import dfbPopInput from "@/components/dfb-pop-input/index.vue";

let changed = false;
const form = reactive({
  _id: "",
  title: "",
  content: "",
  classification_id: "",
  dateTime: "",
  classification: {},
});

// 加载详情
const loadTodo = async (id) => {
  if (id) {
    form._id = id;
  }
  const res = await vk.callFunction({
    url: "client/todo/kh/getTodoDetail",
    data: { _id: id || form._id },
  });
  res.data.content = formatterContent(res.data.content);
  Object.assign(form, res.data);
};

// 格式化内容
const formatterContent = (content) => {
  // 先替换换行符，再匹配网址并替换为 a 标签
  let newContent = content.replace(
    /(https?:\/\/[^\s<]+)/g,
    '<a href="$1" target="_blank">$1</a>'
  );
  return newContent;
};

// 列表数据
const data = reactive({
  list: [],
  total: 0,
  loadmore: "loadmore",
});

const pagination = reactive({
  pageSize: 7,
  pageIndex: 1,
});

const loadData = async () => {
  data.loadmore = "loading";
  try {
    const { data: res } = await uni.vk.callFunction({
      url: "client/todo/kh/getTodoProcessList",
      data: {
        pageSize: pagination.pageSize,
        pageIndex: pagination.pageIndex,
        todo_id: form._id,
      },
    });
    if (pagination.pageIndex === 1) {
      data.list = res.rows;
    } else {
      data.list = [...data.list, ...res.rows];
    }
    data.total = res.total;
    data.loadmore = res.hasMore ? "loadmore" : "nomore";
  } catch (e) {
    console.error(e);
    data.loadmore = "loadmore";
  }
};

// 加载下一页
const nextPage = () => {
  if (data.loadmore !== "loadmore") return;
  pagination.pageIndex++;
  loadData();
};

// 重新加载数据的函数，将页码重置为 1 并调用 loadData 函数加载数据
const reloadData = () => {
  pagination.pageIndex = 1;
  return loadData();
};

// 删除待办
const del = () => {
  uni.vk.confirm("确定要删除改待办吗？", "提示").then((res) => {
    if (res.confirm) {
      uni.vk
        .callFunction({
          url: "client/todo/kh/deleteTodo",
          data: { _id: form._id },
        })
        .then(() => {
          uni.vk.toast("删除成功");
          changed = true;
          uni.navigateBack();
        });
    }
  });
};

// 编辑问题
const edit = () => {
  uni.navigateTo({
    url: "/subPages/todo/addOrEdit?id=" + form._id + "&mode=edit",
  });
};

// 初始化加载
onLoad(async (options) => {
  if (options.id) {
    await loadTodo(options.id);
    await loadData();
  }
});

const submitLoading = ref(false);
let isTodoMode = 2;
const submitTodoProcess = async (text) => {
  if (submitLoading.value) return;
  submitLoading.value = true;
  try {
    if ([0, 1].includes(isTodoMode)) {
      await uni.vk.callFunction({
        url: "client/todo/kh/setTodoStatus",
        data: { status: isTodoMode, _id: form._id },
      });
      form.status = isTodoMode;
      changed = true;
    }
    const url = editTodoProcessItem._id
      ? "client/todo/kh/editTodoProcess"
      : "client/todo/kh/addTodoProcess";
    const data = {
      todo_id: form._id,
      content: text,
    };
    if (editTodoProcessItem._id) data._id = editTodoProcessItem._id;
    await uni.vk.callFunction({
      url: url,
      data,
    });
    submitLoading.value = false;
    uni.vk.toast("操作成功");
    changed = true;
    reloadData();
  } catch (e) {
    changed = true;
    submitLoading.value = false;
  }
};

const showPopInput = ref(false);
const popInputTitle = ref("");
const popInputContent = ref("");
const popInputDefaultValue = ref("");
const editTodoProcessItem = reactive({});
const rules = computed(() => ({
  required: popInputTitle.value !== "提示",
  maxlength: 150,
}));

const toAddProcess = (defaultValue = "") => {
  isTodoMode = 2;
  Object.assign(editTodoProcessItem, { _id: "" });
  popInputDefaultValue.value = defaultValue;
  showPopInput.value = true;
  popInputTitle.value = "填写进展";
  popInputContent.value = "";
};

const toTodoProcessEdit = async (item) => {
  isTodoMode = 2;
  Object.assign(editTodoProcessItem, item);
  popInputDefaultValue.value = item.content;
  showPopInput.value = true;
  popInputTitle.value = "编辑进展";
  popInputContent.value = "";
};

const toCompleteTodo = async (boolean) => {
  isTodoMode = boolean;
  Object.assign(editTodoProcessItem, { _id: "" });
  popInputDefaultValue.value = boolean ? "[完成待办]" : "[取消完成]";
  showPopInput.value = true;
  popInputTitle.value = "提示";
  popInputContent.value = boolean
    ? "即将设置待办状态为已完成，是否继续？"
    : "即将取消待办完成状态，是否继续？";
};

const toTodoProcessDel = (item) => {
  uni.vk.confirm("确定删除吗？", "提示").then((res) => {
    if (res.confirm) {
      uni.vk
        .callFunction({
          url: "client/todo/kh/deleteTodoProcess",
          data: { _id: item._id },
        })
        .then(() => {
          uni.vk.toast("删除成功");
          reloadData();
        });
    }
  });
};

// 操作弹窗
const show = ref(false);
const clickAction = (index) => {
  if (index === 0) {
    edit();
  } else if (index === 1) {
    del();
  }
};

const showProcess = ref(false);
const showProcessObj = ref({});
const toShowProcess = (item) => {
  showProcessObj.value = item;
  showProcess.value = true;
};
const clickActionProcess = (index) => {
  if (index === 0) {
    toTodoProcessEdit(showProcessObj.value);
  } else if (index === 1) {
    toTodoProcessDel(showProcessObj.value);
  }
};

uni.$on("refreshTodoDetail", loadTodo);
onBeforeUnmount(() => {
  uni.$off("refreshTodoDetail", loadTodo);
  if (changed) {
    uni.$emit("refreshTodoList");
  }
});
</script>

<style lang="scss">
.todo-detail {
  padding: 15px 12px;
  position: relative;
  .header {
    font-size: 1.2em;
    font-weight: bold;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      font-size: 18px;
      margin-right: 5px;
      flex: 1;
      user-select: text;
    }
  }

  .content {
    text-indent: 0;
    white-space: pre-wrap; /* 保留所有换行符和空格 */
    user-select: text;
    line-height: 1.8;
    a {
      color: $u-type-primary;
    }
  }
  .tagArea {
    margin-top: 15px;
    margin-bottom: 10px;
    display: flex;
    gap: 5px;
    align-items: center;
    padding: 0 0px 15px;
    border-bottom: 1px solid $u-border-color;
  }
  .answerInputArea {
    padding-bottom: 15px;
    border-bottom: 1px solid $u-border-color;
    margin-bottom: 10px;
    .answerInputAreaTitle {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 2px;
      margin-bottom: 10px;
      & > text {
        font-size: 1em;
        font-weight: 500;
      }
      & > view {
        color: $u-type-primary;
        font-size: 0.9em;
        & > .u-icon {
          margin-right: 2px;
        }
      }
    }
    .answerInputerAreaContent {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 10px;
      font-size: 0.8em;
      .styleButton1 {
        background-color: $u-type-warning-disabled;
      }
      .styleButton2 {
        background-color: $u-type-primary;
        color: #fff;
      }
    }
  }
  .processListArea {
    .processListAreaTitle {
      font-size: 1em;
      font-weight: 500;
      margin-bottom: 10px;
    }
    .alaItem {
      padding: 10px 15px;
      background: #2979ff0a;
      border: 1px dashed #2979ff82;
      margin-bottom: 10px;
      border-radius: 5px;
      .alaItemTitle {
        font-size: 0.9em;
        font-weight: 500;
        margin-bottom: 5px;
        color: $u-content-color;
      }
      .answerItemContent {
        color: $u-main-color;
        word-wrap: break-word;
        text-indent: 0;
        white-space: pre-wrap; /* 保留所有换行符和空格 */
        user-select: text;
      }
      .answerItemTime {
        font-size: 0.9em;
        color: $u-tips-color;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
        .rightIcon {
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
}
</style>
